package com.easytouch.core;

import android.content.Context;
import android.content.Intent;

import com.easytouch.core.utils.Log;


import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android_serialport_api.SerialPort;

public class ScannerThread {
    public static final String SCANNER_BROADCAST = "com.ecloudland.vm7in_portrait.service.ScannerThread";
    public static final String SCANNER_INTENT_QRCODE = "com.ecloudland.vm7in_portrait.service.ScannerThread.intent";
    StringBuffer mHmStringBuffer = new StringBuffer();
    private Log mLogger = new Log("scanner.txt");
    private String device; // 设备号
    private int baudRate; // 扫描波特率
    private SerialPort mSerialPort;
    private boolean isScanedOver = false; // 代表扫描是否完成

    public boolean isScanning = false; //是否正在扫描
    private Context context;
    private OutputStream out;
    private OutputStream out1;

    public ScannerThread(String comport, String baudrate, Context context) {
        this.context = context;
        // 获得配置文件中是否开启扫描枪的字段
//			String mScanConfig = ini.get("scan", "scan");
        // 获得配置文件中的端口号的字段

        mLogger.i("comport is " + comport);
        if (comport == null || "".equals(comport)) {
            comport = "ttymxc3";
        }
        device = comport.length() > 1 ? "/dev/" + comport : "/dev/ttymxc" + comport;
        mLogger.i("device is " + device);
        // 获得配置文件中的传输波特率的字段
        baudRate = Integer.parseInt(baudrate);
        mLogger.i("baudRate is " + baudRate);
    }

//    public ScannerThread() {
//        // 加载配置文件
//        File scan = new File(LSApplication.CACHEPATH + "/set/scan.ini");
//        IniEditor ini = new IniEditor();
//        try {
//            ini.load(scan);
//            // 获得配置文件中是否开启扫描枪的字段
////			String mScanConfig = ini.get("scan", "scan");
//            // 获得配置文件中的端口号的字段
//            String comport = ini.get("comport", "comport");
//            mLogger.i("comport is " + comport);
//            if (comport == null) {
//                comport = "ttymxc3";
//            }
//            device = comport.length() > 1 ? "/dev/" + comport : "/dev/ttymxc" + comport;
//            mLogger.i("device is " + device);
//            // 获得配置文件中的传输波特率的字段
//            baudRate = Integer.parseInt(ini.get("baudrate", "baudrate"));
//            mLogger.i("baudRate is " + baudRate);
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//    }

    public void startScan() {
        new Thread() {
            public void run() {
                // String device = "/dev/ttymxc3";
                try {
                    isScanning = true;
                    mSerialPort = new SerialPort(new File(device), baudRate, 0);
                    String mScanData = doScan();
                    mLogger.i("the value of mScanData is " + mScanData);
                    if (mScanData != null && isScanedOver) { // 发送message的前提：扫描结果不空，并且扫描结束
//						Message msg = handler.obtainMessage();
//						msg.what = 1;
//						msg.obj = mScanData;
//						mLogger.i("001 mScanData is " + mScanData);
//						handler.sendMessage(msg);
                        //TODO
                        mLogger.i("start send broadcast");
                        Intent qrcodeIntent = new Intent(SCANNER_BROADCAST);
                        qrcodeIntent.putExtra(SCANNER_INTENT_QRCODE, mScanData);
                        context.sendBroadcast(qrcodeIntent);
                    }
                } catch (SecurityException e) {
                    mLogger.i("run method SecurityException : "
                            + e.getCause().getMessage());
                } catch (IOException e) {
                    mLogger.i("run method IOException : "
                            + e.getCause().getMessage());
                }
            }
        }.start();
        isScanning = false;
    }

    private String doScan() {
        String sString = null;
        OutputStream out = null;
        InputStream in = null;
        try {
            out = mSerialPort.getOutputStream();
            in = mSerialPort.getInputStream();
            byte[] buffer = new byte[18];
            if (in == null) {
                return null;
            }

            int temp = 0;
            int templen = 0;
            while ((temp = in.read()) != -1) {
                buffer[templen++] = (byte) temp;
                mLogger.i("---  " + templen + "  " + new String(buffer));
                if (templen == 18) {
                    break;
                }
            }
            sString = new String(buffer);
            mLogger.i("aaaa:"+sString);
            if (!"".equals(sString)) {
                isScanedOver = true;
                return sString;
            }
//            int read = in.read(buffer);
//            if (read > 0) {
//                sString = onDataReceived(buffer, read);
//                mLogger.i("读取数据：" + sString);
//                isScanedOver = true;
//                return sString;
//            }

//            String sString = new String(buffer).trim();
//            mLogger.i("读取头：" + sString);


//            if (sString.length() > 0 && !"".equals(sString)) {
//                isScanedOver = true;
//                return sString;
//            } else {
//                mLogger.i("identify QR failed, and stop to scan" + sString);
//                isScanedOver = false;
//                isScanning = false;
//                return sString;
//            }
        } catch (Exception e) {
            e.printStackTrace();
            isScanning = false;
            return null;
        } finally {
            try {
                out.close();
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return sString;
    }

    private String onDataReceived(byte[] buffer, int size) {

        mLogger.i("扫描数据11： " + mHmStringBuffer.toString());
        final String centent = new String(buffer).toString().trim();
        if (!centent.equals("") && centent.indexOf("\"") == -1 && !isMessyCode(centent)) {
            mHmStringBuffer.append(centent);
            return mHmStringBuffer.toString();
        }
        return mHmStringBuffer.toString();
    }

    /**
     * 检测是不是乱码
     */
    public static boolean isMessyCode(String strName) {
        Pattern p = Pattern.compile("\\s*|t*|r*|n*");
        Matcher m = p.matcher(strName);
        String after = m.replaceAll("");
        String temp = after.replaceAll("\\p{P}", "");
        char[] ch = temp.trim().toCharArray();
        float chLength = ch.length;
        float count = 0;
        for (int i = 0; i < ch.length; i++) {
            char c = ch[i];
            if (!Character.isLetterOrDigit(c)) {
                if (!isChinese(c)) {
                    count = count + 1;
                }
            }
        }
        float result = count / chLength;
        if (result > 0.4) {
            return true;
        } else {
            return false;
        }

    }

    /**
     * 检测是不是中文
     */
    public static boolean isChinese(char c) {
        Character.UnicodeBlock ub = Character.UnicodeBlock.of(c);
        if (ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS
                || ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS
                || ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A
                || ub == Character.UnicodeBlock.GENERAL_PUNCTUATION
                || ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION
                || ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS) {
            return true;
        }
        return false;
    }

    private String doScan2() { // 把端口号和波特率写到配置文件中
        try {
            OutputStream out = null;
            out = mSerialPort.getOutputStream();
            InputStream in = null;
            in = mSerialPort.getInputStream();
            byte[] read = new byte[1024];
            for (int i = 0; i < read.length; i++) {
                read[i] = 0x00;
            }
            byte[] data = new byte[3];
            data[0] = (byte) 0x32;
            data[1] = (byte) 0x75;
            data[2] = (byte) 0x01;
            out.write(data);
            out.flush();
            StringBuffer str = new StringBuffer();
            int r = in.read();
            if (r == 0x03) { // 识别二维码成功
                mLogger.i("identify QR successed, and start to scan");
                int len1 = in.read();
                int len2 = in.read();
                int len = 0;
                len1 = len1 & 0xFF;
                len2 = len2 & 0xFF;
                len = (len1 << 8) + len2;
                int count = in.read(read, 0, len);
                if (count > 0) {
                    for (int j = 0; j < len - 2; j++) {
                        char ch = (char) read[j];
                        if (ch >= '0' && ch <= '9') {
                            str.append(String.valueOf(ch));
                        }
                    }
                }
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                mLogger.i("scan QR successed, and the result is "
                        + str.toString());
                isScanedOver = true;
                return str.toString();
            } else {
                mLogger.i("identify QR failed, and stop to scan" + r);
                isScanedOver = false;
                isScanning = false;
                return null;
            }
        } catch (IOException e) {
            isScanning = false;
            mLogger.i("Scan occur IOException : " + e.getCause().getMessage());
        } finally {

        }
        // } catch (SecurityException e) {
        // mLogger.i("Scan occur SecurityException : "
        // + e.getCause().getMessage());
        // } catch (IOException e) {
        // mLogger.i("Scan occur IOException : " + e.getCause().getMessage());
        // }
        mLogger.i("scan QR terminate");
        isScanedOver = false;
        isScanning = false;
        return null;
    }

    public void stopScan() {
        if (mSerialPort != null) {
            mSerialPort.close();
        }
    }

    public void stopScan2() { // 需要把端口号和波特率写到配置文件中
        // String device = "/dev/ttymxc3";
        // try {
        // mSerialPort = new SerialPort(new File(device), 115200, 0);
        OutputStream out = null;
        if (mSerialPort != null) {
            out = mSerialPort.getOutputStream(); // TODO 空指针
            byte[] read = new byte[1024];
            for (int i = 0; i < read.length; i++) {
                read[i] = 0x00;
            }
            byte[] data = new byte[3];
            data[0] = (byte) 0x32;
            data[1] = (byte) 0x75;
            data[2] = (byte) 0x02;
            try {
                out.write(data); // TODO 空指针
                out.flush();
                isScanning = false;
            } catch (IOException e) {
                isScanning = false;
                mLogger.i("stopScan occur IOException : "
                        + e.getCause().getMessage());
            }
        }
        // } catch (SecurityException e) {
        // mLogger.i("stopScan occur SecurityException : "
        // + e.getCause().getMessage());
        // } catch (IOException e) {
        // mLogger.i("stopScan occur IOException : "
        // + e.getCause().getMessage());
        // }
    }
}
